package com.hqyj.javaSpringBoot.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.LogRecord;

/**
 * 删除请求中的 “fuck” 字符串
 */
@WebFilter(filterName = "paramFilter", value = {"/*"})
public class ParamFilter implements Filter {

    private final static Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("==== Do Filter ====");

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 通过包装类HttpServletRequestWrapper操作HttpServletRequest中的参数
        //    直接在new的对象上进行重写
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req){
            @Override
            public String getParameter(String name) {
                String value = super.getParameter(name);
                if (StringUtils.isNotBlank(value)) {
                    value = value.replaceAll("fuck", "***");
                }
                return value;
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);

                //stream api：数组 ---- list ---- 处理数据 ---- 转化为数组
                return Arrays.asList(values)
                        .stream()
                        .map(item -> item.replaceAll("fuck","***"))
                        .toArray(String[] :: new);
            }
        };

        chain.doFilter(wrapper, resp);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("==== Init Filter ====");
    }

    @Override
    public void destroy() {
        LOGGER.debug("==== Destroy Filter ====");
    }
}
